/**
 * 佣金管理
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var angular = require("angular");
    require('authorize');
    require("permission");
    require("angular-route");
    require("angular-ui");
    require("angular-interceptor");
    require('global');
    var util = require("util");
    var ui = require("ui");
    var _ = require("underscore");

    var app = angular.module('app', ['ngRoute', 'ngUI', 'ngInterceptor']);

    function MainController($scope, $q, customPage) {
        $scope.customPage = customPage;

        customPage.query();
    }

    app.controller('MainController', ['$scope', '$q', 'customPage', MainController]);

    function customPageSerivce($http, $q) {
        var service = {
            query: function () {
                var url = '/api/index.php?r=qmyx/custom-page/get-page';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.get(url, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.data = data.data;

                        _.each(service.data, function (record) {
                            if (!service.selectedTable) {
                                service.changeSelectTable(record);
                            }

                            record.RequiredFields = record.RequiredFields.split(',');
                            record.SelectedFields = _.map(record.SelectedFields.split(','), function(field) {
                                var simpleField = field.split('.')[1];

                                return {
                                    field: field,
                                    required: _.contains(record.RequiredFields, field),
                                    dnotRemove: service.isRequired(simpleField),    //dnotRemove为true: 字段必选不能移出
                                    mustRequired:service.isMustRequired(simpleField)//mustRequired为true: 必填不允许更改
                                };
                            });

                            record.SourceFields = _.map(record.SourceFields.split(','), function(field) {
                                return {
                                    field: field,
                                    selected: !!_.find(record.SelectedFields, function(n) {
                                        return n.field == field;
                                    })
                            };
                            });
                        });
                    });
            },

            save: function () {
                var selectedFields = _.map(service.selectedTable.SelectedFields, function(field) {
                    return field.field;
                }).join(',');

                var requiredFields = _.chain(service.selectedTable.SelectedFields)
                    .where({ required: true })
                    .map(function(field) {
                        return field.field;
                    })
                    .value()
                    .join(',');

                var data = {
                    mdl_mobUserPageDesignId: service.selectedTable.mdl_mobUserPageDesignId,
                    SelectedFields: selectedFields,
                    RequiredFields: requiredFields
                };
                var url = '/api/index.php?r=qmyx/custom-page/save-fields';

                return $http.post(url, data)
                    .success(function (data) {
                        ui.showSucTip('保存成功！');
                });
            },

            // 查询字段中文名
            queryFieldsComment: function (record) {
                var url = '/api/index.php?r=qmyx/custom-page/get-fields';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.get(url, { params: { name: record.SourceTables }, timeout: arguments.callee.canceller.promise })
                .success(function (data) {
                    var fieldInfos = data.data;
                    _.each(record.SourceFields, function (field) {
                        var simpleField = field.field.split('.')[1];
                        field.comment = (_.findWhere(fieldInfos, { Name: simpleField }) || {}).DisplayName;
                    });
                    _.each(record.SelectedFields, function (field) {
                        var simpleField = field.field.split('.')[1];
                        field.comment = (_.findWhere(fieldInfos, { Name: simpleField }) || {}).DisplayName;
                    });

                    record.hasComment = true;
                });
            },

            changeSelectTable: function (record) {
                service.selectedTable = record;
                if (!record.hasComment) {
                    service.queryFieldsComment(record);
                }
            },

            selectFields: function() {
                var fields = _.select(service.selectedTable.SourceFields, function(x) {
                    return x.checked;
                });

                _.each(fields, service.selectField);
                service.checkSource();
                service.checkSelected();
            },

            selectField: function(fieldRecord) {
                service.selectedTable.SelectedFields.push({
                    field: fieldRecord.field,
                    comment: fieldRecord.comment
                });

                fieldRecord.selected = true;
                fieldRecord.checked = false;
            },

            unselectFields: function() {
                var fields = _.select(service.selectedTable.SelectedFields, function (x) {
                    return x.checked;
                });

                _.each(fields, service.unselectField);
                service.checkSource();
                service.checkSelected();
            },

            unselectField: function (fieldRecord) {
                var simpleField = fieldRecord.field.split('.')[1];
                if (service.isMustRequired(simpleField)) {
                    return;
                }

                var idx = _.findIndex(service.selectedTable.SelectedFields, function(x) {
                    return x.field == fieldRecord.field;
                });
                service.selectedTable.SelectedFields.splice(idx, 1);

                _.find(service.selectedTable.SourceFields, function(x) {
                    return x.field == fieldRecord.field;
                })
                .selected = false;
            },

            moveup: function (fieldRecord) {
                var idx = _.findIndex(service.selectedTable.SelectedFields, function (x) {
                    return x.field == fieldRecord.field;
                });
                var tmp = service.selectedTable.SelectedFields[idx - 1];
                service.selectedTable.SelectedFields[idx - 1] = fieldRecord;
                service.selectedTable.SelectedFields[idx] = tmp;
            },

            movedown: function (fieldRecord) {
                var idx = _.findIndex(service.selectedTable.SelectedFields, function (x) {
                    return x.field == fieldRecord.field;
                });
                var tmp = service.selectedTable.SelectedFields[idx + 1];
                service.selectedTable.SelectedFields[idx + 1] = fieldRecord;
                service.selectedTable.SelectedFields[idx] = tmp;
            },

            checkSourceAll: function() {
                _.each(service.selectedTable.SourceFields, function (x) {
                    if (!x.selected) {
                        x.checked = service.selectedTable.checkedAll1;
                    }
                });
            },

            checkSource: function () {
                var fields = _.select(function(x) {
                    return !x.selected;
                });
                service.selectedTable.checkedAll1 = fields.length && _.all(fields, function(x) {
                        return x.checked;
                    });
            },

            checkSelectedAll: function () {
                _.each(service.selectedTable.SelectedFields, function (x) {
                    if (!x.dnotRemove) {
                        x.checked = service.selectedTable.checkedAll2;
                    }
                });
            },

            checkSelected: function () {
                var fields = _.where(service.selectedTable.SelectedFields, { dnotRemove: false });
                service.selectedTable.checkedAll2 = fields.length && _.all(fields, _.matcher({ checked: true }));
            },
            isRequired: function (simpleField) {
                var required = {
                    mobile_tel: true,
                    password: true,
                    broker_name: true,
                    cre_no: true,
                    capacity_des: true
                };
                return !!required[simpleField] ;
            },
            isMustRequired: function (simpleField) {
                var required = {
                    mobile_tel: true,
                    password: true,
                    broker_name: true,
                    capacity_des: true
                };
                return !!required[simpleField] ;
            },
            checkRequired: function (fieldRecord) {
                var simpleField = fieldRecord.field.split('.')[1];
                if (this.isMustRequired(simpleField)) {
                    // 不允许取消必填
                    fieldRecord.required = true;
                }
            }
        };
        return service;
    }
    app.factory('customPage', ['$http', '$q', customPageSerivce]);

    angular.bootstrap(document.getElementById('ng-app'), ['app']);
});